﻿using Common.Api.Dtos;
using Cyss.Core.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cyss.TaskManager.Infrastructure
{
    public class MainThread
    {
        /// <summary>
        /// 当前工作Timer
        /// </summary>
        private Timer _timer;

        private List<TaskThreadView> TaskThreads { set; get; }


        public MainThread(List<TaskThreadView> taskThreads)
        {
            TaskThreads = taskThreads;
        }

        public void Start()
        {

            IsClose = false;
            if (_timer == null)
            {
                _timer = new Timer(TimerHandler, null, 0, 1000);
            }
        }

        private void AddTask(TaskThreadView task)
        {
            if (!TaskThreads.Any(x => x.Id == task.Id))
            {
                TaskThreads.Add(task);
            }
        }
        private void RemoveTask(TaskThreadView task)
        {
            if (TaskThreads.Any(x => x.Id == task.Id))
            {
                TaskThreads.Remove(TaskThreads.FirstOrDefault(x => x.Id == task.Id));
            }
        }

        private bool IsClose { set; get; }

        public void Stop()
        {
            IsClose = true;
            _timer = null;
        }

        /// <summary>
        /// 每秒执行一次
        /// </summary>
        /// <param name="state"></param>
        private void TimerHandler(object state)
        {
            if (IsClose)
            {
                return;
            }
            _timer.Change(-1, -1);
            ExecuteAsync();
            _timer.Change(1000, 1000);

        }

        private void ExecuteAsync()
        {

            foreach (var taskThread in TaskThreads)
            {
                if (IsClose)
                {
                    continue;
                }

                ///如果正在执行或服务以及关闭
                if (taskThread.IsRuning || taskThread.State == false)
                {
                    continue;
                }
                if (taskThread.Config.StartDatetime != new TimeSpan(0, 0, 0) && taskThread.Config.StartDatetime > DateTime.Now.TimeOfDay)
                {
                    continue;
                }
                if (taskThread.Config.EndDatetime != new TimeSpan(0, 0, 0) && taskThread.Config.StartDatetime < DateTime.Now.TimeOfDay)
                {
                    continue;
                }
                //循环执行任务
                if (taskThread.Config.TaskExecuteType == TaskExecuteType.loop)
                {

                    if (taskThread.EndDateTime.AddSeconds(taskThread.Config.Interval) < DateTime.Now)
                    {
                        taskThread.ExecuteAsync();
                    }
                }
                //每日定时执行任务
                if (taskThread.Config.TaskExecuteType == TaskExecuteType.Daily)
                {
                    if (taskThread.Config.MaxExecutionTimes > 0 && taskThread.Counter >= taskThread.Config.MaxExecutionTimes)
                    {
                        continue;
                    }

                    if (taskThread.EndDateTime.AddSeconds(taskThread.Config.Interval) < DateTime.Now)
                    {
                        taskThread.ExecuteAsync();
                    }
                }
                //每日定时执行任务
                if (taskThread.Config.TaskExecuteType == TaskExecuteType.Weekly)
                {
                    if (!taskThread.Config.DayOfWeeks.Contains(DateTime.Now.DayOfWeek))
                    {
                        continue;
                    }

                    if (taskThread.Counter > 0 && taskThread.Config.MaxExecutionTimes > taskThread.Counter)
                    {
                        continue;
                    }
                    if (taskThread.EndDateTime.AddSeconds(taskThread.Config.Interval) < DateTime.Now)
                    {
                        taskThread.ExecuteAsync();
                    }
                }

                //每月定时执行任务
                if (taskThread.Config.TaskExecuteType == TaskExecuteType.Month)
                {
                    var day = DateTime.Now.Day;
                    //如果当天是本月最后一天
                    if (DateTime.Now.Day == DateTime.Now.Date.AddDays(-DateTime.Now.Day + 1).AddMonths(1).AddDays(-1).Day)
                    {
                        day = 0;
                    }
                    if (!taskThread.Config.DayOfMonths.Select(x => x.Day).Contains(day))
                    {
                        continue;
                    }

                    if (taskThread.Counter > 0 && taskThread.Config.MaxExecutionTimes > taskThread.Counter)
                    {
                        continue;
                    }
                    if (taskThread.EndDateTime.AddSeconds(taskThread.Config.Interval) < DateTime.Now)
                    {
                        taskThread.ExecuteAsync();
                    }
                }
            }
        }

    }
}
